﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MyWinFormDLL;

namespace MyDLL.HtmlCharConverter
{
    /// <summary>
    /// 工具类
    /// </summary>
    public static class Utils
    {
        /// <summary>
        /// 从Xlsx文件提取Entries并序列化到JSON文件。
        /// </summary>
        /// <param name="xlsxPath">Xlsx文件路径</param>
        /// <param name="jsonPath">JSON文件路径</param>
        public static void SerializeEntriesFromXlsxToFile(string xlsxPath,string jsonPath)
        {
            var dict = GenerateEntriesFromXlsx(xlsxPath);
            JsonUtility.SerializeObjectToFile(dict, jsonPath);
        }

        /// <summary>
        /// 从Xlsx文件提取Entries并序列化为JSON字符串。
        /// </summary>
        /// <param name="xlsxPath">Xlsx文件路径</param>
        public static string SerializeEntriesFromXlsx(string xlsxPath)
        {
            var dict = GenerateEntriesFromXlsx(xlsxPath);
            return JsonUtility.SerializeObject(dict);
        }

        /// <summary>
        /// 从Xlsx文件提取Entries
        /// </summary>
        /// <param name="path">Xlsx文件路径</param>
        public static Dictionary<char, Entry> GenerateEntriesFromXlsx(string path)
        {
            DataTable dt = MyExcelUtility.ExcelOleDbUtility.WorksheetToDataTable(path);
            Dictionary<char, Entry> dict = new Dictionary<char, Entry>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                Entry entry = new Entry()
                {
                    Character = dt.Rows[i]["Character"].ToString().ToCharArray()[0],
                    HtmlEntityNumber = dt.Rows[i]["Entity Number"].ToString(),
                    HtmlEntityName = dt.Rows[i]["Entity Name"].ToString(),
                    Description = dt.Rows[i]["Description"].ToString(),
                    Type = dt.Rows[i]["Type"].ToString(),
                };
                dict.Add(entry.Character, entry);
            }
            return dict;
        }
    }
}
